package com.lanou3g.hw0517.view;

import com.lanou3g.hw0517.commons.Constant;
import com.lanou3g.hw0517.controller.Controller;
import com.lanou3g.hw0517.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Arrays;

@WebServlet(name = "loginServlet", urlPatterns = "/login")
public class loginServlet extends HttpServlet {
    private Controller controller = new Controller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //  获取数据
        String username = request.getParameter("username");
        String pwd = request.getParameter("password");
//        String mul = request.getParameter("mul");
        User user = controller.login(username, pwd);
//        String  = "";

        // TODO 校验
        if (user != null) {
//            msg = "登录成功";
            // 把user 存入session之前,把对象中的密码置空
            user.setPwd("");
            HttpSession session = request.getSession();
            session.setAttribute(Constant.Session.USER, user);
            request.getRequestDispatcher("/index.jsp").forward(request, response);

        } else {
            request.getRequestDispatcher("/sb.jsp").forward(request, response);
        }
//       request.setAttribute("default",);
//        request.getRequestDispatcher("/default.jsp").forward(request, response);
        String mul = request.getParameter("mul");
        if (mul != null) {
            HttpSession session = request.getSession();
            String sessionId = session.getId();
            Cookie cookie = new Cookie("JSessionID", sessionId);
            cookie.setMaxAge(3600 * 24 * 7);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
